package com.hxut.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.hxut.common.lang.Const;
import com.hxut.common.lang.Result;
import com.hxut.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;

/**
 * description: AuthController
 * date: 2022/6/22 18:01
 * author: MR.孙
 */
@SuppressWarnings("all")
@RestController
public class AuthController extends BaseController{

    @Autowired
    private Producer producer;
    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        //随机生成一个uuid(uuid全名Universally Unique Identifier,通用唯一标识码，是一串32位由十六进制和数组组成的字符串)
        String key= UUID.randomUUID().toString();
        String code=producer.createText();//生成五位随机数

        //为了测试
        key="aaaaa";
        code="11111";

        //生成验证码图片
        BufferedImage bfImage=producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bfImage,"jpg",outputStream);


        //把验证码图片进行base64编码
        Base64Encoder encoder= new Base64Encoder();
        String str="data:image/jpeg;base64,";//前缀
        String base64Img=str+encoder.encode(outputStream.toByteArray());

        //把验证码和key存入到redis中
        redisUtils.hset(Const.Captcha,key,code,120);


        //返回json数据
        return Result.success(MapUtil.builder()
                        .put("token",key)
                        .put("captchaImg",base64Img)
                        .build()
                );
    }

    /**
     * @description:  获取用户信息
     * @param principal
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/11 20:19
    */
    @GetMapping("/sys/userInfo")
    public Result getUserInfo(Principal principal){
        String name = principal.getName();
        SysUser sysUser = sysUserService.getByUsername(name);
        return Result.success(
                MapUtil.builder()
                        .put("id",sysUser.getId())
                        .put("username",sysUser.getUsername())
                        .put("avatar",sysUser.getAvatar())
                        .put("created",sysUser.getCreated())
                        .map()
        );
    }
}
